'''
Created on 2011-03-26

@author: t-bone
'''
from django.shortcuts import render_to_response
from django.forms import forms, fields, widgets
from django.template import Context, loader
from google.appengine.api import taskqueue
from google.appengine.runtime import DeadlineExceededError
from django.http import HttpResponseRedirect, HttpResponse
import datetime
from facebook import facebook, urllib2
import logging
import random


def booth(request):
    
    facebook_instance = facebook.FacebookHandler(request)
    
    if request.method == 'POST':
        
        image = request.FILES['picture']
        form = BoothForm(request.POST,request.FILES)
        
        comment = request.POST['comment']
        #if form.is_valid():
            #form.save()
        #test = facebook_instance.facebook.api(u'/me',{u'source': x,'no_story': 1},method='POST',connection_type='/photos')    
        image2 = image.chunks()
        for chunk in image2:
            image3=chunk
            break
        x=y
        acces_token = facebook_instance.facebook.access_token
        out = urllib2.posturl('https://graph.facebook.com/me/photos', [('access_token', acces_token),('no_story','1'),('message',comment)], 
                            [('myfile', 'myimage.jpg', image3)])
        return HttpResponseRedirect('/album/')
    else:

        form = BoothForm()
    
        if facebook_instance.user:
            facebook_instance.set_data({'form' : form})
            t = loader.get_template('booth.html')
        else:
            facebook_instance.set_data()
            t = loader.get_template('welcome.html')
            
        c = Context(facebook_instance.data)
        response = facebook.FacebookResponse(t.render(c))
        response.init_facebook(facebook_instance)
        return response

def webcam(request):
    
    facebook_instance = facebook.FacebookHandler(request)
    facebook_instance.set_data()
    
    if facebook_instance.user:
        t = loader.get_template('webcam.html')
    else:
        t = loader.get_template('webcam.html')
    c = Context(facebook_instance.data)
    response = facebook.FacebookResponse(t.render(c))
    response.init_facebook(facebook_instance)
    return response

def album(request):
    
    facebook_instance = facebook.FacebookHandler(request)
    
    if facebook_instance.user:

        #friends = facebook_instance.facebook.api(u'/me',connection_type='/friends')
        #friends = friends['data']
           
        #logging.info(u'/me API call response: ' + unicode(facebook_dict))
        query = "SELECT uid, name FROM user WHERE is_app_user = 'True' AND uid IN (SELECT uid2 FROM friend WHERE uid1 =" + facebook_instance.facebook.user_id + ")"
        friends = facebook_instance.facebook.fql(query)
        random.shuffle(friends)

        

#===============================================================================
#        rosie = [friend for friend in friends if friend['name']=='Rose Man']
#        rosie_albums = facebook_instance.facebook.api(u'/'+ rosie[0]['id'],connection_type='/albums')
#        rosie_albums = rosie_albums['data']
#        rosie_albums = [album for album in rosie_albums if album['name']=='I (HE)ART (U) (MA(N) ITY']
#        rosie_photos = facebook_instance.facebook.api(u'/'+ rosie_albums[0]['id'],connection_type='/photos')
#        rosie_photos = rosie_photos['data']
        
        query = "SELECT src, caption, src_small, pid, owner, link " \
                "FROM photo " \
                "WHERE aid IN ( SELECT aid FROM album WHERE owner=100000262584115 and name IN ('I (HE)ART (U) (MA(N) ITY 11*11','I (HE)ART U(MA)NITY 22*22') ) " \
                "ORDER BY created LIMIT 0,200" #"AND owner IN (SELECT subject FROM photo_tag WHERE subject=me() OR subject IN ( SELECT uid2 FROM friend WHERE uid1=me()))" \
                
        rosie_photos = facebook_instance.facebook.fql(query)
        query = "SELECT pid, subject FROM photo_tag WHERE pid IN (SELECT pid FROM photo WHERE aid IN ( SELECT aid FROM album WHERE owner=100000262584115 and name IN ('I (HE)ART (U) (MA(N) ITY 11*11','I (HE)ART U(MA)NITY 22*22') ) )"# WHERE subject=me() OR subject IN ( SELECT uid2 FROM friend WHERE uid1=me())"
        photos_tag = facebook_instance.facebook.fql(query)
        
        
#        user_albums = facebook_instance.facebook.api(u'/me', {u'fields': u'albums'})
#        user_albums = user_albums['albums']['data']
#        artform_album = [album for album in user_albums if album['name']=='art-form Photos']
#        user_photos = facebook_instance.facebook.api(u'/'+ artform_album[0]['id'],connection_type='/photos')
#        user_photos = user_photos['data']

        photo_ids = [tag['pid'] for tag in photos_tag if tag['subject']==facebook_instance.facebook.user_id]
        from_rosie_photo = [photo for photo in rosie_photos if photo['pid'] in photo_ids]
        user_photos = from_rosie_photo
        #b = facebook_instance.facebook.fql("SELECT uid, birthday, name FROM user WHERE name='Thierry Ferland' and uid IN ( SELECT uid2 FROM friend WHERE uid1=me() )")
        #c = len(b)
        #x=y
        #a = facebook_instance.facebook.fql("SELECT aid FROM album WHERE owner IN ( SELECT uid2 FROM friend WHERE uid1=me() ) AND name='art-form Photos' ")
        shown_friends = [friend for friend in friends[0:min(3,len(friends))]]

        query = "SELECT src, src_small, caption, link, owner FROM photo WHERE aid IN ( SELECT aid FROM album WHERE owner IN (" \
        + facebook_instance.facebook.user_id
        for friend in shown_friends:
            query = query + "," + str(friend['uid'])  
        query = query + ") AND name='art-form Photos' ) ORDER BY created"
        
        all_photos_from_artform = facebook_instance.facebook.fql(query)
        user_photos.extend([photo for photo in all_photos_from_artform if photo['owner']==facebook_instance.facebook.user_id])
        #query = "SELECT src, src_small, caption, link, owner FROM photo WHERE aid IN ( SELECT aid FROM album WHERE name='art-form Photos' and owner in (SELECT uid2 FROM friend WHERE uid1=me() ) ) ORDER BY created LIMIT 0,25"
        #all_friends_photos = facebook_instance.facebook.fql(query)
        friend_photos = []
        for friend in shown_friends:
            photo_ids = [tag['pid'] for tag in photos_tag if int(tag['subject'])==friend['uid']]
            from_rosie_photo = [photo for photo in rosie_photos if photo['pid'] in photo_ids]
            from_artform = [photo for photo in all_photos_from_artform if int(photo['owner'])==friend['uid']]
  
            if from_artform or from_rosie_photo:
                artform_photos = [friend['name']]
                artform_photos.extend(from_rosie_photo)
                artform_photos.extend(from_artform)
                friend_photos.append(artform_photos)

        #===========================================================================
        # try:
        #    facebook = FacebookHandler(request)
        #    #response.headers[u'P3P'] = u'CP=HONK'  # iframe cookies in IE
        # except Exception, ex:
        #    log_exception(ex)
        #    raise
        #===========================================================================
        facebook_instance.set_data({'user_photo' : user_photos,'friend_photos' : friend_photos})
        
        t = loader.get_template('album.html')
        
    else:
        facebook_instance.set_data()
        t = loader.get_template('welcome.html')
        
    c = Context(facebook_instance.data)
    response = facebook.FacebookResponse(t.render(c))
    response.init_facebook(facebook_instance)
    return response
#===============================================================================
# def log_exception(ex):
#    """Internal logging handler to reduce some App Engine noise in errors"""
#    msg = ((str(ex) or ex.__class__.__name__) +
#            u': \n' + traceback.format_exc())
#    if isinstance(ex, urlfetch.DownloadError) or \
#       isinstance(ex, DeadlineExceededError) or \
#       isinstance(ex, CsrfException) or \
#       isinstance(ex, taskqueue.TransientError):
#        logging.warn(msg)
#    else:
#        logging.error(msg)
#===============================================================================
    
class BoothForm(forms.Form):
    
    picture = fields.FileField(required=False)
    comment = fields.CharField(required=False,widget=widgets.Textarea({'cols': '40', 'rows': '5'}))
    #user = fields.CharField(widget=widgets.HiddenInput(),required=False)

